var express = require('express');
var router = express.Router();
var identityKey = 'skey';
const Util = require('../note/Util');
const db = require('../note/db');
// 登录

// 定义当前路由主页
router.get('/', function(req, res) {
    if (req.session.loginUser) {  // 判断用户是否登录
      console.log('session数据：',req.session.loginUser);
      res.redirect('/');
      return;
    }
   res.render('login', { title: '骚年，你还没有登录', data:{msg:'骚年，你还没有登录！',uname:'suoge'} });
});

router.post('/',function(req,res){
  var sess = req.session;
  console.log('登录参数为：'+JSON.stringify(req.body));
  console.log('加密后的密码-',Util.md5(req.body.password));
  // var user = findUser(req.body.name, req.body.password);

  try {
    db.user.find({
      where:{
        username : req.body.name,
      }
    }).then(ret=>{
      if(ret.password===Util.jiami(req.body.password)){
        req.session.regenerate(function(err) {
            if(err){
                return res.json({ret_code: 2, ret_msg: '登录失败'});
            }

            req.session.loginUser = ret.username;
            req.session.loginUserId = ret.id;
            req.session.loginUserNick = ret.nick;
            // try {
            //   // update
            //   db.user.update({last_login : (Date.parse(new Date())/1000)}, {id : ret.id}).on('success', function(msg){
            //       console.log(msg);
            //   }).on('failure', function(err){
            //       console.log(err);
            //   });
            // } catch (e) {
            //
            // }
            ret.last_login = Date.parse(new Date())/1000;
            ret.save();
            res.json({ret_code: 0, ret_msg: '登录成功'});
        });
      }else{
        res.json({ret_code: 1, ret_msg: '账号或密码错误'});
      }

    }).catch(e=>{
      console.log(e);
      return res.json({ret_code: 1, ret_msg: '账号不存在！'});
    })

  } catch (e) {
    console.log(e);
    return res.json({ret_code: 2, ret_msg: '获取数据失败'});
  }

})

module.exports = router;
